package com.hengxinguotong.zhihuichengjian.ui.device;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.DeviceListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Device;
import com.hengxinguotong.zhihuichengjian.bean.DeviceListRes;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/3/13.
 */

public class DeviceListFragment extends BaseFragment {

    @BindView(R.id.device_lv)
    PullToRefreshListView deviceLv;
    Unbinder unbinder;
    private int pageIndex = 1;
    private String type; //1 进场 2出场   1维修  2保养       1安装    2拆卸
    private int index;  //1 设备进出场   2 设备保养维修     3设备安装拆卸
    private List<Device> devices;
    private DeviceListAdapter deviceListAdapter;
    private String interfaceString;
    private Handler handler = new Handler();
    Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            deviceLv.setRefreshing();
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_devicelist, null);
        unbinder = ButterKnife.bind(this, contentView);
        deviceLv.setMode(PullToRefreshBase.Mode.BOTH);
        type = getArguments().getString("type");
        index = getArguments().getInt("index", 1);
        if (index == 3) {
            interfaceString = "/equipmentRegister/queryDisassemblyList/";
        } else if (index == 2) {
            interfaceString = "/equipmentRegister/queryMaintenanceList/";
        } else {
            interfaceString = "/equipmentRegister/queryOutRecordList/";
        }
        deviceLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getDeviceInfo(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getDeviceInfo(null);
            }
        });

        deviceLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Device device = devices.get(position - 1);
                if (index == 3) {
                    Intent intent = new Intent(getActivity(), DeviceDisassembleActivity.class);
                    intent.putExtra("type", device.getType());
                    intent.putExtra("device", device);
                    startActivity(intent);
                } else if (index == 2) {
                    Intent intent = new Intent(getActivity(), DeviceMaintainActivity.class);
                    intent.putExtra("type", device.getType());
                    intent.putExtra("device", device);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), DeviceInOutActivity.class);
                    intent.putExtra("device", device);
                    intent.putExtra("type", device.getType());
                    startActivity(intent);
                }
            }
        });
        return contentView;
    }

    @Override
    public void onLazyLoad() {
        handler.postDelayed(MyRunnable, 500);

    }

    public static DeviceListFragment newInstance(String type, int index) {
        DeviceListFragment fragment = new DeviceListFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        args.putInt("index", index);
        fragment.setArguments(args);
        return fragment;
    }

    private void getDeviceInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            if (DeviceListActivity.IN.equals(type) || DeviceMainTainListActivity.REPAIR.equals(type)) {
                jsonObject.put("type", 1);
            } else if (DeviceMainTainListActivity.MAINTAIN.equals(type) || DeviceListActivity.OUT.equals(type)) {
                jsonObject.put("type", 2);
            } else if (DeviceDisassembleListActivity.INSTALL.equals(type) || DeviceDisassembleListActivity.UNINSTALL.equals(type)) {
                jsonObject.put("type", 3);
            }
            jsonObject.put("constructionId", SPUtil.getString(getActivity(),"constructionid"));
            jsonObject.put("pageNum", pageIndex);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), interfaceString + SPUtil.getString(getActivity(),"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (deviceLv.isRefreshing()) {
                    deviceLv.onRefreshComplete();
                }

                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DeviceListRes deviceListRes = gson.fromJson(json, DeviceListRes.class);
                    addData(deviceListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    public void reLoad(){
        if(deviceLv!=null){
            handler.postDelayed(MyRunnable, 500);
        }
    }

    private void addData(List<Device> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(deviceLv);
            }else{
                dismissEmptyView();
            }
            devices = datas;
            deviceListAdapter = new DeviceListAdapter(devices, getActivity());
            deviceLv.setAdapter(deviceListAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                deviceLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            devices.addAll(datas);
            deviceListAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            deviceLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
